import React, { Component } from 'react';
import { NavBar, Icon, ListView } from 'antd-mobile';
import axios from 'axios'
import style from './index.module.scss'
import './index.module.scss'
import ReactDOM from 'react-dom'

function MyBody(props) {
  // console.log(props)
  return (
    <div className="am-list-body my-body">
      {props.children}
    </div>
  );
}
const data = [
  {
    img: 'https://zos.alipayobjects.com/rmsportal/dKbkpPXKfvZzWCM.png',
    title: 'Meet hotel',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
  {
    img: 'https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png',
    title: 'McDonald\'s invites you',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
  {
    img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
    title: 'Eat the week',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
];

const NUM_SECTIONS = 3;
const NUM_ROWS_PER_SECTION = 3;
let pageIndex = 0;

const dataBlobs = {};
let sectionIDs = [];
let rowIDs = [];
function genData(pIndex = 0) {
  for (let i = 0; i < NUM_SECTIONS; i++) {
    const ii = (pIndex * NUM_SECTIONS) + i;
    const sectionName = `Section ${ii}`;
    sectionIDs.push(sectionName);
    dataBlobs[sectionName] = sectionName;
    rowIDs[ii] = [];

    for (let jj = 0; jj < NUM_ROWS_PER_SECTION; jj++) {
      const rowName = `S${ii}, R${jj}`;
      rowIDs[ii].push(rowName);
      dataBlobs[rowName] = rowName;
    }
  }
  sectionIDs = [...sectionIDs];
  console.log('1111',sectionIDs)
  rowIDs = [...rowIDs];
  console.log('2222',rowIDs)

}

class Com extends Component {
  constructor (props) {
    super(props)
    const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
    const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];
    // console.log('333',getSectionData)
    console.log('444',getRowData)

    const dataSource = new ListView.DataSource({
      getRowData,
      getSectionHeaderData: getSectionData,
      rowHasChanged: (row1, row2) => row1 !== row2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });
    this.state={
      travellist: {},
      travelid: null,
      author: {},
      answer: [],
      loves: [],
      col: false,
      hasMore: true,
      dataSource,
      isLoading: true,
      height: document.documentElement.clientHeight * 3 / 4,
    }
  }

  componentWillMount(){
    //console.log(this.props.location.travelid)//传递过来的所有参数
    // console.log(this.props.location.state.travelid)//val值
    const id = localStorage.getItem("id")
    // 从本地取得此用户id，然后与请求来的数据中的loves的数据去匹对，如果有则col是true表示关注，否则为未关注
    // 这里用col模拟了一下
    const col = localStorage.getItem("col") ? true : false
    this.setState({
      travelid: id,
      col: col
    })
}
  componentDidMount () {
    axios.get(`http://rap2.taobao.org:38080/app/mock/244731/api/traveldetail?travelid=${this.state.travelid}`).then(res=>{
      console.log(res)
      this.setState({
        travellist: res.data.data,
        author: res.data.data.author,
        answer: res.data.data.answer,
        loves:res.data.data.loves,
      })
    })

    const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop
    // simulate initial Ajax
    setTimeout(() => {
      genData();
      console.log(dataBlobs,sectionIDs,rowIDs)
      this.setState({
        dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlobs, sectionIDs, rowIDs),
        isLoading: false,
        height: hei,
      });
    }, 600);
  }

  onEndReached = (event) => {
    console.log('reach end', event);

    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    this.setState({ isLoading: true });
    setTimeout(() => {
      genData(++pageIndex);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlobs, sectionIDs, rowIDs),
        isLoading: false,
      });
    }, 1000);
  }

  // 点击改变关注状态，如果之前是关注则要在数据库把此数据删除，之前是未关注则要向数据库添加此项数据
  changelike = () => {

    this.setState({
      col: !this.state.col
    })
  }
  render() {
    // console.log(this.state.height)
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    let index = data.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = data.length - 1;
      }
      const obj = data[index--];
      console.log(obj)
      return (
        <div key={rowID} style={{ padding: '0 15px' }}>
          <div
            style={{
              lineHeight: '50px',
              color: '#888',
              fontSize: 18,
              borderBottom: '1px solid #F6F6F6',
            }}
          >{obj.title}</div>
          <div style={{ display: '-webkit-box', display: 'flex', padding: '15px 0' }}>
            <img style={{ height: '64px', marginRight: '15px' }} src={obj.img} alt="" />
            <div style={{ lineHeight: 1 }}>
              <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>{obj.des}</div>
              <div><span style={{ fontSize: '30px', color: '#FF6E27' }}>35</span>¥ {rowID}</div>
            </div>
          </div>
        </div>
      );
    };

    return (
      <div className='box'>
        {/* 头部 */}
        <header className='header'>
          <NavBar
            mode="light"
            // icon={<Icon type={require('./../../left.svg')} />}
            icon={ <span className="iconfont icon-fanhui" style={{ fontSize: '0.23rem', color: '#00B145' }}></span>}
            onLeftClick={() => {
              this.props.history.go(-1)
            }}
            rightContent={[
              <Icon key="0" type="ellipsis" color='#00B145' style={{ marginRight: '0.13rem' }} />
            ]}
            >精选游记
          </NavBar>
        </header>
        <div className='content'>
          {/* 景点图像区域 */}
          <div>
            <img src={this.state.travellist.img} alt="" style={{ width:"100%",height: '1.6rem'}}/>
            <p style={{ padding: '0.1rem 0.2rem 0 0.15rem', fontSize: '0.14rem', fontWeight: 'bold',lineHeight: '0.21rem', color:'rgba(51,51,51,1)'}}>{this.state.travellist.desc}</p>
            { this.state.travellist.hot ? '' : <img style={{width: '0.49rem', height: '0.17rem', marginLeft: '0.15rem', marginBottom: '0.08rem'}} src='/images/jinghua.png' alt=''></img>}
          </div>
          {/* 作者区域 */}
          <div className={style.author}>
            {/* 发布作者头像 */}
            <div className={style.avatar}>
              <img src={this.state.author.avatar} alt=""/>
               <div>
                 <p>{this.state.author.name}</p>
                 <span>{this.state.author.pubdata}</span>
                </div>     
            </div>
            {/* 发布时间 */}
            <p style={{ fontSize: '0.12rem', opacity: 0.8, color: 'rgba(102,102,102,1)', width: '100%', textAlign: 'left', paddingLeft: '0.15rem', marginBottom: '0.1rem'}}>拍摄于{this.state.author.photodata}</p>
            {/* 点赞者 */}
            <div className={style.love}>
              <div>
              {
                this.state.loves.map((item,index)=>{
                  if(index<6){
                    return <img key={item.userid} src={item.avatar} alt=""/>
                  }
                  return
                })
              }
              </div>
              {
                this.state.col ? <span className='iconfont icon-weibiaoti105' onClick={this.changelike} style={{ fontSize: '0.19rem',color: '#d81e06'}}>{this.state.loves.length > 99 ? '99+': this.state.loves.length}</span> :
                <span className='iconfont icon-Group-' onClick={this.changelike} style={{ fontSize: '0.19rem'}}>{this.state.loves.length > 99 ? '99+': this.state.loves.length}</span>
              }
            </div>
          </div>
          {/* 回复区域 */}
          <p style={{padding: '0 0 0.15rem 0.15rem',fontWeight:'bold',color:'rgba(51,51,51,1)' ,fontSize: '0.14rem'}}>回复</p>
          <div className={style.answer}>
            {/* 此处应为当前用户得头像 */}
            <img src={this.state.author.avatar} alt=""/>
            <input type="text" placeholder='写个回复，pick楼主'/>
            <span>摇一句</span>
          </div>
          {/* <ul>
              {
                this.state.answer.map(item=>{
                  return <li>
                    <img src={item.avatar} alt=""/>
                    <div>
                      <p>{item.username}</p>
                      <p>{item.desc}</p>
                    </div>
                    <i></i>
                  </li>
                })
              }
          </ul> */}
          <ListView
        ref={el => this.lv = el}
        dataSource={this.state.dataSource}
        renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
          {this.state.isLoading ? 'Loading...' : 'Loaded'}
        </div>)}
        renderBodyComponent={() => <MyBody />}
        renderRow={row}
        renderSeparator={separator}
        style={{
          height: this.state.height,
          overflow: 'none'
        }}
        pageSize={4}
        // onScroll={() => { console.log('scroll'); }}
        // scrollRenderAheadDistance={500}
        // onEndReached={this.onEndReached}
        // onEndReachedThreshold={10}
      />
        </div>
      </div>
    );
  }
}

export default Com
